<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>实体变更日志详细测试</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <style>
        .diff-highlight {
            background-color: #fff3cd;
            color: #856404;
        }
        .field-description {
            font-weight: bold;
            color: #007bff;
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <h2>实体变更日志详细测试</h2>
        
        <div class="card mb-4">
            <div class="card-header">
                <h5>创建测试实体</h5>
            </div>
            <div class="card-body">
                <form id="createForm">
                    <div class="form-group">
                        <label for="productName">商品名称</label>
                        <input type="text" class="form-control" id="productName" value="苹果">
                    </div>
                    <div class="form-group">
                        <label for="price">价格</label>
                        <input type="number" class="form-control" id="price" value="5.50" step="0.01">
                    </div>
                    <div class="form-group">
                        <label for="description">描述</label>
                        <input type="text" class="form-control" id="description" value="新鲜红富士苹果">
                    </div>
                    <div class="form-group form-check">
                        <input type="checkbox" class="form-check-input" id="enabled" checked>
                        <label class="form-check-label" for="enabled">是否启用</label>
                    </div>
                    <button type="button" class="btn btn-primary" onclick="createEntity()">创建实体</button>
                </form>
            </div>
        </div>
        
        <div class="card mb-4">
            <div class="card-header">
                <h5>更新测试实体</h5>
            </div>
            <div class="card-body">
                <form id="updateForm">
                    <div class="form-group">
                        <label for="updateId">实体ID</label>
                        <input type="number" class="form-control" id="updateId" value="1">
                    </div>
                    <div class="form-group">
                        <label for="updateProductName">商品名称</label>
                        <input type="text" class="form-control" id="updateProductName" value="红富士苹果">
                    </div>
                    <div class="form-group">
                        <label for="updatePrice">价格</label>
                        <input type="number" class="form-control" id="updatePrice" value="6.00" step="0.01">
                    </div>
                    <div class="form-group">
                        <label for="updateDescription">描述</label>
                        <input type="text" class="form-control" id="updateDescription" value="新鲜优质红富士苹果">
                    </div>
                    <button type="button" class="btn btn-warning" onclick="updateEntity()">更新实体</button>
                </form>
            </div>
        </div>
        
        <div class="card">
            <div class="card-header">
                <h5>查看变更日志</h5>
            </div>
            <div class="card-body">
                <button type="button" class="btn btn-info" onclick="viewLogs()">查看日志</button>
                <div id="logsContainer" class="mt-3"></div>
            </div>
        </div>
    </div>
    
    <!-- 详情模态框 -->
    <div class="modal fade" id="detailModal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-xl" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">变更详情</h5>
                    <button type="button" class="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div id="detailContent">
                        <!-- 详情内容将通过JavaScript动态加载 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 创建实体
        function createEntity() {
            const entity = {
                productName: $('#productName').val(),
                price: $('#price').val(),
                description: $('#description').val(),
                enabled: $('#enabled').is(':checked'),
                createTime: new Date()
            };
            
            $.ajax({
                url: '/test/entity/create',
                method: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(entity),
                success: function(response) {
                    alert('实体创建成功');
                },
                error: function() {
                    alert('实体创建失败');
                }
            });
        }
        
        // 更新实体
        function updateEntity() {
            const entity = {
                id: $('#updateId').val(),
                productName: $('#updateProductName').val(),
                price: $('#updatePrice').val(),
                description: $('#updateDescription').val(),
                enabled: true,
                createTime: new Date()
            };
            
            $.ajax({
                url: '/test/entity/update',
                method: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(entity),
                success: function(response) {
                    alert('实体更新成功');
                },
                error: function() {
                    alert('实体更新失败');
                }
            });
        }
        
        // 查看日志
        function viewLogs() {
            $.get('/sys/entityChangeLog/list?page=1&limit=10', function(response) {
                if (response.code === 0) {
                    renderLogs(response.page.list);
                } else {
                    alert('获取日志数据失败: ' + response.msg);
                }
            }).fail(function() {
                alert('请求失败，请检查网络连接');
            });
        }
        
        // 渲染日志列表
        function renderLogs(logs) {
            let html = '<div class="table-responsive"><table class="table table-striped table-bordered"><thead><tr><th>操作时间</th><th>操作用户</th><th>实体类名</th><th>操作类型</th><th>操作</th></tr></thead><tbody>';
            
            if (!logs || logs.length === 0) {
                html += '<tr><td colspan="5" class="text-center">暂无数据</td></tr>';
            } else {
                logs.forEach(log => {
                    html += `
                        <tr>
                            <td>${log.createDate}</td>
                            <td>${log.username}</td>
                            <td>${log.entityClass ? log.entityClass.substring(log.entityClass.lastIndexOf('.') + 1) : ''}</td>
                            <td>${getOperationTypeText(log.operationType)}</td>
                            <td><button class="btn btn-sm btn-info" onclick="showDetail(${log.id})">详情</button></td>
                        </tr>
                    `;
                });
            }
            
            html += '</tbody></table></div>';
            $('#logsContainer').html(html);
        }
        
        // 获取操作类型文本
        function getOperationTypeText(operationType) {
            switch (operationType) {
                case 'INSERT': return '<span class="badge badge-success">新增</span>';
                case 'UPDATE': return '<span class="badge badge-warning">修改</span>';
                case 'DELETE': return '<span class="badge badge-danger">删除</span>';
                default: return operationType;
            }
        }
        
        // 显示详情
        function showDetail(logId) {
            $.get('/sys/entityChangeLog/info?id=' + logId, function(response) {
                if (response.code === 0) {
                    renderDetailModal(response.data);
                } else {
                    alert('获取详情失败: ' + response.msg);
                }
            }).fail(function() {
                alert('请求失败，请检查网络连接');
            });
        }
        
        // 渲染详情模态框
        function renderDetailModal(log) {
            let detailHtml = `
                <div class="row">
                    <div class="col-md-6">
                        <h6>基本信息</h6>
                        <table class="table table-sm">
                            <tr><td>操作时间:</td><td>${log.createDate}</td></tr>
                            <tr><td>操作用户:</td><td>${log.username}</td></tr>
                            <tr><td>实体类名:</td><td>${log.entityClass || ''}</td></tr>
                            <tr><td>操作类型:</td><td>${getOperationTypeText(log.operationType)}</td></tr>
                            <tr><td>实体ID:</td><td>${log.entityId || ''}</td></tr>
                            <tr><td>操作描述:</td><td>${log.operation}</td></tr>
                        </table>
                    </div>
                </div>
            `;
            
            // 如果有详细的字段变更信息，则显示
            if (log.detailedFieldChanges && log.detailedFieldChanges.length > 0) {
                detailHtml += `
                    <div class="row mt-4">
                        <div class="col-12">
                            <h6>详细变更信息（包含字段描述）</h6>
                            <div class="table-responsive">
                                <table class="table table-bordered table-sm">
                                    <thead>
                                        <tr>
                                            <th>字段路径</th>
                                            <th>字段描述</th>
                                            <th>变更前</th>
                                            <th>变更后</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${renderDetailedDiffTable(log.detailedFieldChanges)}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                `;
            } else if (log.fieldChanges && Object.keys(log.fieldChanges).length > 0) {
                // 显示标准字段变更详情
                detailHtml += `
                    <div class="row mt-4">
                        <div class="col-12">
                            <h6>变更详情</h6>
                            <div class="table-responsive">
                                <table class="table table-bordered table-sm">
                                    <thead>
                                        <tr>
                                            <th>字段</th>
                                            <th>变更前</th>
                                            <th>变更后</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        ${renderStandardDiffTable(log.fieldChanges)}
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                `;
            }
            
            $('#detailContent').html(detailHtml);
            $('#detailModal').modal('show');
        }
        
        // 渲染详细差异表格（包含字段描述）
        function renderDetailedDiffTable(detailedChanges) {
            let html = '';
            
            detailedChanges.forEach(change => {
                const fieldName = change.fieldName || '';
                const fieldDescription = change.fieldDescription || fieldName;
                const oldValue = change.oldValue !== undefined ? formatValue(change.oldValue) : '-';
                const newValue = change.newValue !== undefined ? formatValue(change.newValue) : '-';
                const isChanged = change.oldValue !== change.newValue;
                
                html += `
                    <tr ${isChanged ? 'class="diff-highlight"' : ''}>
                        <td>${fieldName}</td>
                        <td class="field-description">${fieldDescription}</td>
                        <td>${oldValue}</td>
                        <td>${newValue}</td>
                    </tr>
                `;
            });
            
            return html;
        }
        
        // 渲染标准差异表格
        function renderStandardDiffTable(fieldChanges) {
            let html = '';
            
            for (const [fieldName, values] of Object.entries(fieldChanges)) {
                const oldValue = values[0] !== undefined ? formatValue(values[0]) : '-';
                const newValue = values[1] !== undefined ? formatValue(values[1]) : '-';
                const isChanged = values[0] !== values[1];
                
                html += `
                    <tr ${isChanged ? 'class="diff-highlight"' : ''}>
                        <td>${fieldName}</td>
                        <td>${oldValue}</td>
                        <td>${newValue}</td>
                    </tr>
                `;
            }
            
            return html;
        }
        
        // 格式化值显示
        function formatValue(value) {
            if (value === null) return 'null';
            if (value === undefined) return 'undefined';
            if (typeof value === 'object') return JSON.stringify(value, null, 2);
            return String(value);
        }
    </script>
</body>
</html>